import os, logging
log = logging.getLogger('PbrtRenderUtils')

from Katana import Nodes2DAPI, Nodes3DAPI, RenderingAPI

from Nodes3DAPI import Rendering
from Nodes3DAPI import RenderingUtil

def _buildRenderCommand():
    pass


def buildRenderCommand(producer, renderSettings, nodeName, renderTime,
    mainSequenceId, sequenceIDMap, useID, commonChildEnv):

    # get the number of render threads
    numThreads = renderSettings.get('render threads', 1)

    # Check for external listener
    externalListenerInfo = Nodes2DAPI.GetExternalRenderListenerInfo()
    if externalListenerInfo is None:
        raise RuntimeError, "External render listener is not active."

    # Write support files
    tmpProductStateTableFilename = Rendering.writeProductStateTable(RenderingUtil.GetTmpLocalFile)
    tmpProducerTextFilename = Rendering.writeProducerText(RenderingUtil.GetTmpLocalFile, producer)

    Rendering.global_tmp_filenames[mainSequenceId] = (tmpProductStateTableFilename,
                                                      tmpProducerTextFilename)

    interactiveOutputsList = []
    interactiveOutputs = Nodes3DAPI.GetInteractiveOutputs(producer)

    if interactiveOutputs:
        for outputName in interactiveOutputs:
            channel = _getChannelName(producer, outputName)
            try:
                sequenceId = sequenceIDMap[outputName]
                interactiveOutputsList.append((outputName, sequenceId, channel))
            except Exception:
                errorMessage = "sequenceId for output '%s' not found in map" % outputName
                raise RuntimeError, errorMessage
    else:
        interactiveOutputsList.append(('primary', mainSequenceId, _getChannelName(producer, 'primary')))

    windowOrigin, originalSize, cropWindow, screenWindow, dataWindow = \
        Rendering.coordinateNoodling(renderSettings)

    modifyChildEnv = {}

    pythonPath = os.environ.get('KATANA_PYTHON_LIBS', '')
    if 'PYTHONPATH' in os.environ:
        if pythonPath: pythonPath += ':'
        pythonPath += os.environ['PYTHONPATH']
    modifyChildEnv['PYTHONPATH'] = pythonPath

    spiImportPackages = os.environ.get('KATANA_SPIMPORT_PACKAGES', '')
    if 'SPIMPORT_PACKAGES' in os.environ:
        if spiImportPackages: spiImportPackages += ':'
        spiImportPackages += os.environ['SPIMPORT_PACKAGES']
    modifyChildEnv['SPIMPORT_PACKAGES'] = spiImportPackages
    modifyChildEnv['SPIMPORT_NOWARNING'] = '1'

    # add ARNOLD_LD_LIBRARY_PATH into LD_LIBRARY_PATH
    libPath = os.environ.get('LD_LIBRARY_PATH', '')
    pbrttree = os.environ.get('PBRTTREE')
    if pbrttree:
        pbrtLibPath = pbrttree + '/lib'
        modifyChildEnv['LD_LIBRARY_PATH'] = pbrtLibPath + ':' + libPath

    envCmd = ''
    if modifyChildEnv or commonChildEnv:
        envCmd = 'env '
        for key, value in modifyChildEnv.iteritems():
            envCmd += '%s=%s ' % (key,value)
        for key, value in commonChildEnv.iteritems():
            envCmd += '%s=%s ' % (key,value)


    # Get the arnold executable
    pluginPath = RenderingAPI.RenderPlugins.GetRendererPluginBinDir("pbrt")
    pbrtExecutable = os.path.join(pluginPath, "pbrt-katana")

    cmd = envCmd + ' '
    cmd += pbrtExecutable
    cmd += ' --recipeFile %s' % tmpProducerTextFilename
    cmd += ' --productStateTable %s' % tmpProductStateTableFilename
    cmd += ' --outputAddress %s' % externalListenerInfo[0]
    cmd += ' --nCores %s' % numThreads
    cmd += ' --outputAddress %s' % externalListenerInfo[0]
    cmd += ' --width %d' % (dataWindow[2]-dataWindow[0])
    cmd += ' --height %d' % (dataWindow[3]-dataWindow[1])
    cmd += ' --cropWindow %f,%f,%f,%f' % cropWindow
    cmd += ' --screenWindow %f,%f,%f,%f' % screenWindow
    cmd += ' --frameTime %f' % renderTime
    cmd += ' --frameName %s' % nodeName
    cmd += ' --frameOrigin %d,%d' % windowOrigin
    cmd += ' --displayWindowSize %d,%d' % originalSize
    if useID:
        cmd += ' --generateIDs'

    for interactiveOutput in interactiveOutputsList:
        cmd += ' --outputChannel %s' % interactiveOutput[2]
        cmd += ' --frameID %d' % interactiveOutput[1]


    return cmd, 'pbrt_v2', pbrtExecutable

def _getChannelName(producer, outputName):
    channelAttr = producer.getDelimitedLocalAttribute("renderSettings.outputs.%s.rendererSettings.channel" % outputName)
    if channelAttr:
        channel = channelAttr.getData()[0]
    else:
        channel = 'RGBA'

    return channel
